import React, { Component, Fragment, useEffect, useState, useRef } from 'react'
import axios from 'axios'
import './city.scss'
import { CityItemType, letterArrType } from './city.d'

const CityPage = () => {
  const [rightIndex, setRightIndex] = useState(0)
  const [cityList, setCityList] = useState<letterArrType[]>([])
  const [offsetTopArr, setoffsetTopArr] = useState<number[]>([])
  const cityWrapper = useRef<HTMLDivElement | null>(null)
  const leftItem = useRef<HTMLDivElement | null>(null)

  /* eslint-disable */
  const getCityList = async () => {
    const res = await axios.get('/city.json')
    // console.log(res.data, 'res')
    const cityData: CityItemType[] = res.data
    // 1. 处理一级数据，字母数组，children: [] 准备数据结构
    const letterArr: letterArrType[] = []
    // const arr = []
    cityData.forEach((item) => {
      letterArr.push({ letter: item.letter, children: [] })
    })
    // 2. 排序
    letterArr.sort((a, b) => (a.letter > b.letter ? 1 : -1))
    // console.log('letterArr:', letterArr) // [{letter: 'A', children: []}]
    // 去重：遍历去重复，查找,借助对象，对象key值，唯一性，A:
    // 3. 处理二级数据。children
    // 4. 去重
    const hash: any = {} // {A: true}
    const arr = letterArr.reduce(function (item: letterArrType[], next) {
      hash[next.letter] ? '' : (hash[next.letter] = true && item.push(next))
      return item
    }, [])
    // 如果一个数组中，有很多，隐式转换为false的值的话，可以借助filter去重 (filter返回值为true的值)
    const brr = arr.filter((v) => v.letter)
    //
    cityData.forEach((item) => {
      brr.forEach((v) => {
        if (v.letter === item.letter) {
          v.children.push(item)
        }
      })
    })
    setCityList(brr)
    // console.log('brr:', brr)
    /* eslint-disable */
  }

  useEffect(() => {
    getCityList()
  }, [])
  // 将左侧每一个字母盒子的offetTop存储在一个数组，方便后续使用
  useEffect(() => {
    const target: NodeListOf<HTMLDivElement> = document.querySelectorAll('.left-city-item')
    let arr: number[] = []
    target.forEach((item) => {
      arr.push(item.offsetTop)
    })
    setoffsetTopArr(arr)
  }, [cityList])

  const handleScroll = () => {
    // item: 监听到的元素
    offsetTopArr.forEach((v, i) => {
      if (cityWrapper.current) {
        if (cityWrapper.current.scrollTop >= v) {
          setRightIndex(i)
        }
      }
    })
  }
  const handleAlpha = (index: number) => {
    console.log((document.querySelectorAll('.left-city-item')[index] as HTMLDivElement).offsetTop)
    if (cityWrapper.current) {
      cityWrapper.current.scrollTop = (document.querySelectorAll('.left-city-item')[index] as HTMLDivElement).offsetTop
    }
  }
  const handleCityItem = () => {}
  return (
    <div className="city-container">
      <div className="city-wrapper" ref={cityWrapper} onScroll={handleScroll}>
        <div className="left-city">
          {cityList.map((item) => {
            return (
              <div key={item.letter} ref={leftItem} className="left-city-item">
                <h1 className="left-letter">{item.letter}</h1>
                <ul className="left-city-box">
                  {item.children.map((v) => {
                    return (
                      <li key={v.id} onClick={() => handleCityItem()}>
                        {v.name}
                      </li>
                    )
                  })}
                </ul>
              </div>
            )
          })}
        </div>

        <ul className="right-alpha">
          <Fragment>
            {cityList.map((item, i) => {
              return (
                <li key={i} onClick={() => handleAlpha(i)} className={rightIndex === i ? 'active' : ''}>
                  {item.letter}
                </li>
              )
            })}
          </Fragment>
        </ul>
      </div>
    </div>
  )
}

export default CityPage
